import React, { useState, useEffect, useRef } from 'react';
import { connect } from 'umi';
import styles from './index.less';
import SwingColComponent from '@/components/SwingComponent/SwingColComponent';
import SwingItemComponent from '@/components/SwingComponent/SwingItemComponent';
import { Spin, Select, DatePicker, Empty } from 'antd';
const { Option } = Select;
import { last } from 'lodash';

import {
  getTimeRange,
  getPermisstion,
} from 'enoad-component-web/dist/src/core/util';

const TitleFilter = ({ title, fetchAllData }) => {
  const [selectedValue, setSelectedValue] = useState('thisWeek');
  const [rangeTime, setRangeTime] = useState([]);

  const timeRef = useRef(null);

  const options = [
    {
      label: '今日',
      value: 'today',
    },
    {
      label: '昨日',
      value: 'yesterday',
    },
    {
      label: '本周',
      value: 'thisWeek',
    },
    {
      label: '上周',
      value: 'lastWeek',
    },
    {
      label: '本月',
      value: 'thisMonth',
    },
    {
      label: '自定义',
      value: 'system',
    },
  ];
  useEffect(() => {
    if (selectedValue !== 'system') {
      const timeRange = getTimeRange(selectedValue, '');
      fetchAllData && fetchAllData(timeRange);
    } else if (rangeTime && timeRef.current) {
      const timeRange = getTimeRange(selectedValue, timeRef.current);
      fetchAllData && fetchAllData(timeRange);
    }
  }, [selectedValue]);

  return (
    <div className={styles.titleFilterView}>
      <span className={styles.title}>{title}</span>
      {fetchAllData && (
        <Select
          className={styles.selectView}
          showArrow={true}
          value={selectedValue}
          onChange={(value) => {
            setSelectedValue(value);
          }}
        >
          {options.map((item) => (
            <Option key={item.value} value={item.value}>
              {item.label}
            </Option>
          ))}
        </Select>
      )}
      {fetchAllData && selectedValue === 'system' && (
        <DatePicker.RangePicker
          className={styles.dateRangePicker}
          format="YYYY-MM-DD"
          value={rangeTime}
          onChange={(data, datastr) => {
            setRangeTime(data);
            timeRef.current = datastr;
          }}
          onOpenChange={(open) => {
            if (!open && timeRef.current) {
              const timeRange = getTimeRange(selectedValue, timeRef.current);
              fetchAllData && fetchAllData(timeRange);
            }
          }}
        />
      )}
    </div>
  );
};

/**
 * 泳道入口。
 * @param props
 * @returns
 */
const Swing = (props) => {
  const { dispatch, loading, dataSource, taskStatus } = props;
  const [activeId, setActiveId] = useState(0);

  const [timeRange, setTimeRange] = useState({});
  const cardLoading = loading.effects['enoadTask/fetchData'];

  const fetchAllData = (orTimeRange) => {
    setTimeRange(orTimeRange);
    dispatch({ type: 'enoadTask/fetchConfig', payload: { apiKey: 'SystemTask' } });
    dispatch({
      type: 'enoadTask/fetchData',
      payload: { apiKey: 'SystemTask', ...orTimeRange },
    });
  };
  /**
   * 传入被拖拽任务项的 id
   */
  const onDragStart = (id: number) => {
    setActiveId(id);
  };

  const dragTo = (status: any) => {
    let record =
      dataSource &&
      dataSource.find((item) => {
        return activeId === item._id;
      });
    let params = {
      ...record,
      taskStatus: JSON.stringify(status),
      updateTime: new Date().getTime(),
    };
    delete params._id;
    //调用接口更新该条数据状态。
    dispatch({
      type: 'enoadTask/updateEntity',
      payload: {
        apiKey: 'SystemTask',
        _id: record._id,
        params,
      },
    }).then((res) => {
      if (res) {
        //如果数据更新成功，则重新刷新数据。
        dispatch({
          type: 'enoadTask/fetchData',
          payload: { apiKey: 'SystemTask', ...timeRange },
        });
      }
    });
    cancelSelect();
  };

  const cancelSelect = () => {
    setActiveId(0);
  };

  //该泳道是否可以拖入。
  const canDragIn = (status: { id: number; name: string }) => {
    if (getPermisstion('Task_create') || getPermisstion('Task_edit')) {
      let end = last(taskStatus) || {};
      if (activeId !== null) {
        let record =
          dataSource &&
          dataSource.find((item) => {
            return activeId === item._id;
          });
        if (record && record.taskStatus) {
          let taskStatus = JSON.parse(record.taskStatus);
          if (taskStatus.id === end.id) {
            //数据在最后一列，不能向回移动。
            return false;
          }
          let taskUPId = taskStatus.id + 1;
          let taskBCId = taskStatus.id - 1;
          //只能拖拽到自己相邻泳道。
          return taskUPId === status.id || taskBCId === status.id;
        }
      }
    }
    return false;
  };

  return (
    <Spin spinning={cardLoading}>
      <TitleFilter title={'任务面板'} fetchAllData={fetchAllData} />
      <div className={styles.taskWrapper}>
        {taskStatus &&
          taskStatus.map((status: { id: number; name: string }) => (
            <SwingColComponent
              status={status}
              key={status.id}
              dragTo={dragTo}
              title={status.name}
              canDragIn={canDragIn(status)}
              statusSize={taskStatus.length}
            >
              {dataSource
                .filter((t) => JSON.parse(t.taskStatus).id === status.id)
                .map((t) => (
                  <SwingItemComponent
                    key={t._id}
                    id={t._id}
                    data={t}
                    onDragStart={onDragStart}
                    onDragEnd={cancelSelect}
                  />
                ))}
            </SwingColComponent>
          ))}
      </div>
    </Spin>
  );
};
export default connect(({ enoadTask, loading }) => ({
  ...enoadTask,
  loading,
}))(Swing);
